package com.heima.wemedia.service.impl;

import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONArray;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsAutoScanSerciveImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    public void autoScanWmNews(Integer id) {
        // 1、查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("文章不存在，自媒体文章审核失败");
        }

        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            // 从内容中提取纯文本内容和图片
            Map<String, Object> testAndImages = this.handleTextAndImages(wmNews);

            // 2、审核文本内容 阿里云接口
            boolean isTextScan = this.handleTextScan(String.valueOf(testAndImages.get("content")), wmNews);
            if (!isTextScan) {
                return;
            }

            // 3、审核图片 阿里云接口
            boolean isImageScan = this.handleImageScan((List<String>) testAndImages.get("images"), wmNews);
            if (!isImageScan) {
                return;
            }

            // 4、审核成功，保存app端的相关文章数据
            ResponseResult responseResult = this.saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("文章审核，保存app端相关文章数据失败 !");
            }

            // 回填article_id
            wmNews.setArticleId((Long) responseResult.getData());

            this.updateWmNews(wmNews, (short) 9, "审核成功");
        }
    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 保存app端相关的文章数据
     *
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();

        // 属性拷贝
        BeanUtils.copyProperties(wmNews, dto);

        // 文章的布局
        dto.setLayout(wmNews.getType());
        // 频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        // 作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        // 设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }

        dto.setCreatedTime(new Date());

        return articleClient.saveArticle(dto);
    }

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 审核图片
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if ( images == null || images.isEmpty()) {
            return true;
        }

        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        // 下载图片到minio中
        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);
            imageList.add(bytes);
        }

        // 审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {
                if (map.get("suggestion").equals("block")) { // 审核失败
                    flag = false;
                    this.updateWmNews(wmNews, 2, "当前文章中存在违规内容");
                }
                if (map.get("suggestion").equals("review")) { // 不确定信息，需要人工审核
                    flag = false;
                    this.updateWmNews(wmNews, 3, "当前文章中存在不确定内容 ");
                }
            }
        } catch (Exception e) {
            flag = false;
            Console.log(e.getMessage() + " !");
        }

        return flag;
    }

    /**
     * 1、从自媒体文章的内容中提取文本和图片
     * 2、提取文章的封面图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // 存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        // 1、从自媒体文章的内容中提取文本和图片
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    images.add((String) map.get("value"));
                }
            }
        }

        // 2、提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuilder.toString());
        resultMap.put("image", images);

        return resultMap;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核纯文本内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        String titleAndContent = wmNews.getTitle() + "-" + content;

        boolean flag = true;
        if (content.isEmpty() && wmNews.getTitle().isEmpty()) {
            return true;
        }

        try {
            Map map = greenTextScan.greeTextScan(titleAndContent);
            if (map != null) {
                if (map.get("suggestion").equals("block")) { // 审核失败
                    flag = false;
                    this.updateWmNews(wmNews, 2, "当前文章中存在违规内容");
                }
                if (map.get("suggestion").equals("review")) { // 不确定信息，需要人工审核
                    flag = false;
                    this.updateWmNews(wmNews, 3, "当前文章中存在不确定内容 ");
                }
            }
        } catch (Exception e) {
            flag = false;
            Console.log(e.getMessage() + " !");
        }
        return flag;
    }

    /**
     * 修改文章内容
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, int status, String reason) {
        wmNews.setStatus((short) status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

}


